//
//  BJArticleInfoViewController.m
//  BowJoy
//
//  Created by  on 2024/5/22.
//

#import "BJArticleInfoViewController.h"
#import "BJArticleHeaderViewTableViewCell.h"
#import "BJArticleInfoViewTableViewCell.h"
#import "BJArticleCommentTableViewCell.h"
#import<AVFoundation/AVFoundation.h>
#import <AVFoundation/AVFoundation.h>
#import "BJDVoiceTouchView.h"
#import <SVGAPlayer/SVGAPlayer.h>
#import "SVGAParser.h"

@interface BJArticleInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headerIcon;
@property (weak, nonatomic) IBOutlet UILabel *nikeNameL;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UITextField *textField;


@property (strong,nonatomic) NSMutableArray<BJAnchorWallModelData *> *records;
@property (weak, nonatomic) IBOutlet UIButton *voiceBtn;

@property(nonatomic)BOOL isVoice;
@property (weak, nonatomic) IBOutlet UIView *holdSpeakView;

@property(nonatomic,strong)AVAudioRecorder*recoder;

@property(nonatomic,strong)AVAudioPlayer*playerVoice;
@property(nonatomic,strong)NSString*fileName;

@property (nonatomic,strong)NSTimer *times;
@property (nonatomic,assign)NSInteger timeCount;



//音频功能
@property (nonatomic, strong) UIImageView     *voiceIconImage;
@property (nonatomic, strong) UILabel         *voiceIocnTitleLable;
@property (nonatomic, strong) UIView          *voiceImageSuperView;
@property (nonatomic, assign) BOOL            voiceIsCancel;
@property (nonatomic, assign) BOOL            voiceRecognitionIsEnd;
@property (nonatomic, assign) BOOL            touchIsEnd;
@property (nonatomic, strong) UIImageView     *voiceBottomImage;

@property (nonatomic, strong) BJDVoiceTouchView *gesturesView;//继承长按手势视图
@property (nonatomic, strong) SVGAPlayer *voicePlayer;
@property (nonatomic, strong) SVGAParser *parser;

@property (nonatomic,assign) NSInteger indexRow;


@property (weak, nonatomic) IBOutlet UIImageView *follewIcon;


@end

@implementation BJArticleInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.timeCount = 0;
    self.customNaviBar.hidden = YES;
    self.isVoice = NO;
    self.records = [[NSMutableArray alloc]init];
    if(self.model.avatar){
        [self.headerIcon sd_setImageWithURL:[NSURL URLWithString:self.model.avatar] completed:nil];
    }else{
        self.headerIcon.image = [UIImage imageNamed:@"ic_head_1"];
    }

    
    self.nikeNameL.text = [self getLenghtStr:self.model.nickname withCount:5];
    self.textField.delegate = self;

    self.follewIcon.image = self.model.isFriend ? [UIImage imageNamed:@"icon_followed"]:[UIImage imageNamed:@"icon_follow"];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"BJArticleHeaderViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"BJArticleHeaderViewTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BJArticleInfoViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"BJArticleInfoViewTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BJArticleCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"BJArticleCommentTableViewCell"];

    self.tableView.rowHeight = UITableViewAutomaticDimension;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
    
    
    [ASHUD showASLoading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ASHUD hideHUD];
        NSArray *dataQueryList = [[BJFMDBCommentManager sharedManager] queryWithUserId:self.model.userId];
        if (dataQueryList.count>0) {
            self.records = [[NSMutableArray alloc]initWithArray:dataQueryList];
            [self.tableView reloadData];
        }
    });


    
    kWeakSelf(weakSelf)

    BJDVoiceTouchView *gesturesView = [[BJDVoiceTouchView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [self.holdSpeakView addSubview:gesturesView];
    [gesturesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.holdSpeakView);
        make.right.equalTo(self.holdSpeakView);
        make.height.mas_equalTo(36);
        make.centerX.equalTo(self.holdSpeakView);
    }];
    self.gesturesView = gesturesView;
    self.gesturesView.areaY=-80;//设置滑动高度
    self.gesturesView.clickTime=0.5;//设置长按时间
    gesturesView.touchBegan = ^(){

        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
             //判断是否询问过用户授权麦克风（否则检测麦克风权限，会被APP询问授权弹窗打断）
             if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {
                 // 未询问过用户是否授权，进行第一次询问
                 //这里是关键 ！！！
                 AVAudioSession *avSession = [AVAudioSession sharedInstance];
                 
                 if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
                     
                     [avSession requestRecordPermission:^(BOOL available) {
                         NSLog(@"第一次访问") ;
                     }];
                 }
             }else {
                 AVAudioSession *avSession = [AVAudioSession sharedInstance];
                 
                 if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
                     
                     [avSession requestRecordPermission:^(BOOL available) {
                         if (!available) {
                             //提示用户开启
                             [ASHUD showWithText:@"You have not authorised this permission." afterDelay:1];

                         }else{
                             //已经打开
//                             开始录音
                                 [self startRecoder];
                                 self.timeCount = 0;
                                 self.times = [NSTimer scheduledTimerWithTimeInterval:1 block:^(NSTimer * _Nonnull timer) {
                                     self.timeCount ++;
                                 } repeats:YES];
                             
                                 [weakSelf touchDidBegan];
                         }
                     }];
                 }
                 
             }
                 


 
    };
    gesturesView.upglide = ^(){
        //在区域内
        [weakSelf touchupglide];
    };
    gesturesView.down = ^(){
        //不在区域内
        [weakSelf touchDown];
    };
    gesturesView.touchSendEnd = ^(){
//        NSLog(@"+++++++++++++++++发送");
        //松开发送

        [weakSelf touchDidEnd];
        //手势结束之后，结束录音s
        [self endRecoder];
        [self.times invalidate];
        self.times = nil;
        if (self.timeCount < 1) {
            [ASHUD showWithText:@"The voice length must be greater than 1 second" afterDelay:1];
            return;
        }
    //结束录音
        BJAnchorWallModelData *item = [[BJAnchorWallModelData alloc]init];
        item.isVoice = YES;
        item.voiceFileName = self.fileName;
        item.voiceTime = self.timeCount;
        item.userId = self.model.userId;
        item.followNum = 0;
        [self.records addObject:item];
        self.textField.text = @"";
        
        self.model.commentNum = self.records.count;
        [[BJFMDBManager sharedManager] uptadeDataWithCommentNum:self.model.commentNum andUserId:self.model.userId];
        
        [self.textField resignFirstResponder];
        

        [ASHUD showASLoading];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [ASHUD hideHUD];
            [[BJFMDBCommentManager sharedManager] insertWitModel:item];
            [self.tableView reloadData];
            NSIndexPath *bottomIndex = [NSIndexPath indexPathForRow:(self.records.count+1) inSection:0];
            [self.tableView scrollToRowAtIndexPath:bottomIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    };
    gesturesView.touchCancelEnd = ^(){
        //松开取消
        [weakSelf touchDidEnd];
//        NSLog(@"+++++++++++++++++取消");
    };

    [gesturesView.voiceButton setTitle:@"Hold to speak" forState:UIControlStateNormal];
    [gesturesView.voiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    gesturesView.voiceButton.backgroundColor=[UIColor colorWithHexString:@"#6DFDEE"];
    
}
- (NSString *)getLenghtStr:(NSString *)str withCount:(NSInteger)count{
    NSString * str1 = str;
    if (str.length>count){
        NSRange range = [str rangeOfComposedCharacterSequenceAtIndex:count];
        NSString *subStr = [str substringToIndex:range.location];
        str1 = [NSString stringWithFormat:@"%@...",subStr];
    }
    
    return str1;
}

-(void)touchDidBegan{
    if (!self.voiceIconImage) {
       
        UIView *voiceImageSuperView = [[UIView alloc] init];
        [self.view addSubview:voiceImageSuperView];
        voiceImageSuperView.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.6];
        self.voiceImageSuperView = voiceImageSuperView;
        voiceImageSuperView.makeCons(^{
            make.edge.constants(0);
        });
        
        UIView *voiceImageBgSuperView = [[UIView alloc] init];
        [voiceImageSuperView addSubview:voiceImageBgSuperView];
        voiceImageBgSuperView.makeCons(^{
            make.center.constants(0);
            make.width.height.constants(200);
        });

        
        self.voicePlayer = [[SVGAPlayer alloc] init];
       [voiceImageBgSuperView addSubview:self.voicePlayer];
        self.voicePlayer.makeCons(^{
            make.center.constants(0);
            make.width.constants(129);
            make.height.constants(85);
        });
        
        UIImageView *voiceIconImage = [[UIImageView alloc] init];
        self.voiceIconImage = voiceIconImage;
        voiceIconImage.image = [UIImage imageNamed:@"icon_voice_cancel"];
        [voiceImageBgSuperView addSubview:voiceIconImage];
        voiceIconImage.makeCons(^{
            make.center.constants(0);
            make.width.constants(129);
            make.height.constants(85);
        });
        

        UILabel *voiceIocnTitleLable = [[UILabel alloc] init];
        self.voiceIocnTitleLable = voiceIocnTitleLable;
        [voiceImageBgSuperView addSubview:voiceIocnTitleLable];
        voiceIocnTitleLable.textColor = [UIColor whiteColor];
        voiceIocnTitleLable.font = [UIFont systemFontOfSize:16];
        voiceIocnTitleLable.makeCons(^{
            make.centerX.constants(0);
            make.bottom.view(voiceImageBgSuperView).bottom.constants(-10);
        });
        
        UIView *voiceBottomView = [[UIView alloc] init];
        [voiceImageSuperView addSubview:voiceBottomView];
        voiceBottomView.makeCons(^{
            make.bottom.constants(0);
            make.left.constants(0);
            make.right.constants(0);
            make.height.constants(200);
        });
        
        UIImageView *bottomIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_voice_bg"]];
        [voiceBottomView addSubview:bottomIcon];
        bottomIcon.makeCons(^{
            make.bottom.constants(0);
            make.left.constants(0);
            make.right.constants(0);
            make.height.constants(138);
        });
        
        UIImageView *voiceBottomIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_voice_send"]];
        [voiceBottomView addSubview:voiceBottomIcon];
        self.voiceBottomImage = voiceBottomIcon;
        voiceBottomIcon.makeCons(^{
            make.bottom.constants(-35);
            make.centerX.constants(0);
            make.height.width.constants(63);
        });
        
    }
    self.voiceImageSuperView.hidden = NO;
    self.voiceIconImage.hidden = YES;
    self.parser = [[SVGAParser alloc]init];
    [self.parser parseWithNamed:@"voice_send" inBundle:[NSBundle mainBundle] completionBlock:^(SVGAVideoEntity * _Nonnull videoItem) {
    if(videoItem !=nil) {
          self.voicePlayer.videoItem= videoItem;
        [self.voicePlayer startAnimation];
        }
    }failureBlock:^(NSError*_Nonnullerror) {

    }];
    self.voicePlayer.hidden = NO;


    self.voiceIocnTitleLable.text = @"release send";
    self.voiceIsCancel = NO;
    self.voiceRecognitionIsEnd = NO;
    self.touchIsEnd = NO;
    [_gesturesView.voiceButton setTitle:@"松开发送" forState:UIControlStateNormal];
  
}

-(void)touchupglide{
    self.voiceIsCancel = YES;
    self.voiceIocnTitleLable.text = @"release cancel";
    self.self.voiceBottomImage.image = [UIImage imageNamed:@"icon_release_cancel"];
    self.voiceIconImage.hidden = NO;
    [self.voicePlayer stopAnimation];
    self.voicePlayer.hidden = YES;

}

-(void)touchDown{
    self.voiceIsCancel = NO;
    self.voiceIconImage.hidden = YES;
    self.voicePlayer.hidden = NO;
    [self.voicePlayer startAnimation];
    self.voiceBottomImage.image = [UIImage imageNamed:@"icon_voice_send"];
    self.voiceIocnTitleLable.text = @"release send";
}

-(void)touchDidEnd{
    self.voiceImageSuperView.hidden = YES;
    self.touchIsEnd = YES;
    self.voiceBottomImage.image = [UIImage imageNamed:@"icon_voice_send"];
    self.voiceIocnTitleLable.text = @"release send";
    [_gesturesView.voiceButton setTitle:@"Hold to speak" forState:UIControlStateNormal];
    
}




-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [_textField resignFirstResponder];
}
- (IBAction)clickBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)clickMoreBtn:(id)sender {
    ReportBlock *reportBlock =[[ReportBlock alloc]initWithIsBlock:self.model.isFriend isFriend:self.model.isFriend userId:[self.model.userId longLongValue]];
    kWeakSelf(weakSelf)

    [reportBlock setFollowClickBlock:^(BOOL follow) {
        self.model.isFriend = follow;
        [[BJFMDBManager sharedManager] uptadeDataWithFrend:follow andUserId:self.model.userId];
        [weakSelf.tableView reloadData];
        if (follow) {
            self.model.isFriend = YES;
            self.follewIcon.image = [UIImage imageNamed:@"icon_followed"];
            [BJUserManager sharedManager].followingNum ++;
        }else{
            self.model.isFriend = NO;

            self.follewIcon.image = [UIImage imageNamed:@"icon_follow"];

            [BJUserManager sharedManager].followingNum --;
        }
        

    }];//关注
    [reportBlock setBlockClickBlock:^(BOOL block) {
        [[BJFMDBManager sharedManager] deleteDataWithUserId:self.model.userId];
        [[BJFMDBBlockManager sharedManager] insertWitModel:self.model];
        [BJUserManager sharedManager].blockNum ++;

        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];//拉黑
    
    [reportBlock show];
}


- (IBAction)clickFollewBtn:(id)sender {
    if (!self.model.isFriend) {
        [[BJNetManager shareNetManager]postAddFriendWithFollowUserId:[self.model.userId longLongValue] completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
            NSDictionary *dict = responseObj;
            NSInteger code = [dict[@"code"]integerValue];
            if(!error && code == 0){
                [BJUserManager sharedManager].followingNum ++;

                self.model.isFriend = YES;
                self.follewIcon.image = [UIImage imageNamed:@"icon_followed"];
                [ASHUD showWithText:@"Follow Successfully" afterDelay:2];
            }
            [[BJFMDBManager sharedManager] uptadeDataWithFrend:YES andUserId:self.model.userId];

        }];

    }else{
        [[BJNetManager shareNetManager]postDeleteFriendWithFollowUserId:self.model.userId completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
            NSDictionary *dict = responseObj;
            NSInteger code = [dict[@"code"]integerValue];
            if(!error && code == 0){
               self.follewIcon.image = [UIImage imageNamed:@"icon_follow"];
                [[BJFMDBManager sharedManager] uptadeDataWithFrend:NO andUserId:self.model.userId];
                [BJUserManager sharedManager].followingNum --;

                self.model.isFriend = NO;
                [ASHUD showWithText:@"Unfollow Successfully" afterDelay:2];
            }

        }];
    }



}

- (IBAction)clickVoceBtn:(id)sender {
    self.isVoice = !self.isVoice;
    [self.voiceBtn setImage:self.isVoice?[UIImage imageNamed:@"icon_text"]:[UIImage imageNamed:@"icon_voie"] forState:UIControlStateNormal];
    self.holdSpeakView.hidden = !self.isVoice;
}

- (IBAction)clickSendMessageBtn:(id)sender {
    if ([self.textField.text isEqualToString: @""] || self.textField.text == nil) {
        [ASHUD showError:@"Please enter a comment ！"];
        return;
    }
    
    BJAnchorWallModelData *item = [[BJAnchorWallModelData alloc]init];
    item.isVoice = NO;
    item.voiceFileName = self.textField.text;
    item.voiceTime = self.timeCount;
    item.userId = self.model.userId;
    item.followNum = 0;
    [self.records addObject:item];
    self.textField.text = @"";
    

    self.model.commentNum = self.records.count;
    [[BJFMDBManager sharedManager] uptadeDataWithCommentNum:self.model.commentNum andUserId:self.model.userId];

    [self.textField resignFirstResponder];

    [ASHUD showASLoading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ASHUD hideHUD];
        [[BJFMDBCommentManager sharedManager] insertWitModel:item];
        [self.tableView reloadData];
        NSIndexPath *bottomIndex = [NSIndexPath indexPathForRow:(self.records.count+1) inSection:0];
        [self.tableView scrollToRowAtIndexPath:bottomIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.textField.text = textField.text;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2+self.records.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        BJArticleHeaderViewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BJArticleHeaderViewTableViewCell"];
        if (cell == nil){
            cell = [[BJArticleHeaderViewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BJArticleHeaderViewTableViewCell"];
        }
        cell.model = self.model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return  cell;
    }else if(indexPath.row == 1){
        BJArticleInfoViewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BJArticleInfoViewTableViewCell"];
        if (cell == nil){
            cell = [[BJArticleInfoViewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BJArticleInfoViewTableViewCell"];
        }
        kWeakSelf(weakSelf)

        cell.model = self.model;
        cell.followBtn.onClick(^{
            if (!self.model.isLike) {
                weakSelf.model.isLike = YES;
                weakSelf.model.followNum ++;
                [weakSelf.tableView reloadData];
            }else{
                weakSelf.model.isLike = NO;
                weakSelf.model.followNum --;
                [weakSelf.tableView reloadData];
               
            }     
            [[BJFMDBManager sharedManager] uptadeDataWithLike:self.model.isLike andUserId:self.model.userId];

        });
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return  cell;
        
    }else{
        BJArticleCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BJArticleCommentTableViewCell"];
        if (cell == nil){
            cell = [[BJArticleCommentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BJArticleCommentTableViewCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
        
        BJAnchorWallModelData *item = self.records[indexPath.row-2];
        cell.model = item;
        
        cell.follewBtn.onClick(^{
            item.isFriend = !item.isFriend;
            if (item.isFriend) {
                item.followNum ++;
            }else{
                item.followNum --;
            }
            [self.tableView reloadData];
        });
        cell.voiceBaView.onClick(^{
            UInt32 sessionCategory =  kAudioSessionCategory_MediaPlayback;
            AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,sizeof(sessionCategory), &sessionCategory);
            UInt32 audioRouteOverride =kAudioSessionOverrideAudioRoute_Speaker;
            AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,sizeof(audioRouteOverride), &audioRouteOverride);
            self.indexRow = indexPath.row;
            item.isOpenVoice = YES;
            self.fileName = item.voiceFileName;
            //播放暂停都有方法但是在真机上默认为耳机模式需要设置音频播放的输出源
            [self.playerVoice play];
            [self.tableView reloadData];
        });
 
        return  cell;
    }

    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.textField resignFirstResponder];
}


-(AVAudioPlayer*)playerVoice {
    if(_playerVoice==nil) {
        _playerVoice= [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:self.fileName] error:nil];
        _playerVoice.volume=1.0;
        _playerVoice.delegate=self;
    }
    return _playerVoice;
}


//开始录音

-(void)startRecoder {
    //激活AVAudioSession
    NSError*error =nil;
    AVAudioSession*session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    if(session !=nil) {
     [session setActive:YES error:nil];
    }else{
    NSLog(@"Session error = %@",error);
    }
    //设置AVAudioRecorder的setting属性
    NSDictionary*recoderSettings = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithFloat:16000.0],AVSampleRateKey,[NSNumber numberWithInt:kAudioFormatAppleIMA4],AVFormatIDKey,[NSNumber numberWithInt:1],AVNumberOfChannelsKey,[NSNumber numberWithInt:AVAudioQualityMax],AVEncoderAudioQualityKey,nil];
    //初始化recodeer对象
    NSString*tempDir =NSTemporaryDirectory();
    NSString *fileName = [NSString stringWithFormat:@"record_%f.caf", [NSDate date].timeIntervalSince1970];
    NSString*urlPatch = [tempDir stringByAppendingString:fileName];
    self.fileName = urlPatch;
    self.recoder= [[AVAudioRecorder alloc]initWithURL:[NSURL fileURLWithPath:urlPatch] settings:recoderSettings error:nil];
    //开始录音
    [self.recoder record];
}

//结束录音

-(void)endRecoder {
    [self.recoder stop];
    self.recoder=nil;
    self.playerVoice=nil;

}


//但是代码写到这里，在播放录音的过程中，只能播放第一个所以每次播放完，要多播放的类进行释放在代理方法里面设置 步骤是先遵循AVAudioPlayerDelegate代理  设置_player.delegate = self;

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    self.playerVoice=nil;
    BJAnchorWallModelData *item = self.records[self.indexRow-2];
    item.isOpenVoice = NO;
    [self.tableView reloadData];
}


@end
